• 2024-06-14
  • unique

MikroTik Cloudflare DDNS

  1. create API token with permission to Edit DNS: https://developers.cloudflare.com/fundamentals/api/get-started/create-token/

  2. get Zone ID (ZONE_ID) from domain page: https://developers.cloudflare.com/fundamentals/setup/find-account-and-zone-ids/

curl --request GET \
  --url https://api.cloudflare.com/client/v4/zones/***ZONE_ID***/dns_records \
  --header 'Authorization: Bearer ***REDACTED***' \
  --header 'Content-Type: application/json'

get result[].id from the A record which should be updated with DDNS

  1. update the following lines
:local cfzoneid "***ZONE_ID***" // zone id from step 2.
:local cfdnsrecordid "***REDACTED***" // id retrieved in 2.
:local cftoken "***REDACTED***" // token generatend in step 1.
:local cfemail "***REDACTED***" // account mail
:local cfdnshost "***REDACTED***" // sub/domain to update

:local publicinterface "***REDACTED***" // inteface to check for public ip

in this script

:local dateTime ([ /system clock get date ] . " " . [ / system clock get time ]);

:local cfzoneid "***ZONE_ID***"
:local cfdnsrecordid "***REDACTED***"
:local cftoken "***REDACTED***"
:local cfemail "***REDACTED***"
:local cfdnshost "***REDACTED***"

:local publicinterface "***REDACTED***"
:local ipddns [:resolve $cfdnshost server=1.1.1.1]
:local ipfresh [ /ip address get [/ip address find interface=$publicinterface ] address ]
:set ipfresh [:pick $ipfresh 0 [:find $ipfresh "/" -1]]

:local cfurl "https://api.cloudflare.com/client/v4/zones/$cfzoneid/dns_records/$cfdnsrecordid"
:local cfDataDNS "{\"type\":\"A\",\"name\":\"$cfdnshost\",\"content\":\"$ipfresh\",\"ttl\":60,\"proxied\":false,\"comment\":\"last update: $dateTime\"}"
:local cfHeader "X-Auth-Email: $cfemail,Authorization: Bearer $cftoken,Content-Type: application/json"

:if ($ipddns != $ipfresh) do={
   /tool fetch url=$cfurl http-data=$cfDataDNS http-header-field=$cfHeader http-method=put keep-result=no
}
  1. add script System -> Scripts to Mikrotik with policy read, write, test
  2. run script /system script run SCRIPT_NAME on schedule System -> Scheduler

source: https://vectops.com/post/2023/configure-mikrotik-with-cloudflare-ddns/